import UIKit

@objc public protocol TFcourseDownloadControllerDelegate:AnyObject {
    func getDownLoad(status:TalkfunDownloadStatus)
}
class TFcourseDownloadController: UIViewController ,UITableViewDelegate,UITableViewDataSource,TalkfunDownloadManagerDelegate {

    /** 代理对象 */
    @objc public weak var delegate: TFcourseDownloadControllerDelegate?

    /**下载的标识*/
    var downTags:NSInteger = 0;
    let cell_Id:NSString = "TalkfunTableViewCell"
    let RememberNickID:NSString = "rememberNickID1"
    let RememberID:NSString = "rememberID"
    let downlistTableview = UITableView()
    //下载列表返回的数据
    let dataSource = NSMutableArray()
    //下载列表
    //记住选中的cell的indexPath
    let selectedArray = NSMutableArray()
    let footerView = UIView()
    //下载管理对象
    let downloadManager = TalkfunDownloadManager.share()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.downloadManager.delegate = self
        self.downlistTableview.frame = self.view.bounds
        self.downlistTableview.delegate = self;
        self.downlistTableview.dataSource = self;
        self.downlistTableview.separatorStyle = .none;
        self.downlistTableview.backgroundColor = UIColor.white
        self.view.addSubview(self.downlistTableview)
        self.downlistTableview.register(TalkfunTableViewCell.self, forCellReuseIdentifier: self.cell_Id as String)
        self.footerViewChildControl()
    }
    
    func footerViewChildControl()
    {
        self.footerView.frame = CGRect(x: 0, y: TalkfunSharedTools.getMainScreen().size.height , width: self.view.frame.width, height: 50)

        self.footerView.backgroundColor = UIColor(red: 255 / 255.0, green: 255 / 255.0, blue: 255 / 255.0, alpha: 1.0)
        
        let  lineLab = UILabel()
        let lineLabW:CGFloat =  TalkfunSharedTools.getMainScreen().size.width
        lineLab.frame =  CGRect(x: 0, y: 0, width:lineLabW , height: 1)
        lineLab.backgroundColor = UIColor(red: 220 / 255.0, green: 228 / 255.0, blue: 235 / 255.0, alpha: 1.0)

        let selectAllBtn = UIButton()
        selectAllBtn.frame = CGRect(x: 0, y: 10, width: (TalkfunSharedTools.getMainScreen().size.width - 64) / 2.0, height: self.footerView.frame.height - 20)
        selectAllBtn.setTitle("全选", for: .normal)
        selectAllBtn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        selectAllBtn.titleLabel?.textAlignment = .center;
        selectAllBtn.setTitleColor(UIColor(red: 66/255.0, green: 67/255.0, blue: 68/255.0, alpha: 1.0), for: .normal)
        selectAllBtn.addTarget(self, action: #selector(bianjiClick(btn:)), for: .touchUpInside)
        selectAllBtn.isSelected = false;
        selectAllBtn.tag = 20;

        let editBtn = UIButton()
        let editBtnW = (TalkfunSharedTools.getMainScreen().width - 64 ) / 2
        editBtn.frame = CGRect(x: editBtnW , y: 10, width: editBtnW, height: self.footerView.frame.height - 20)
        editBtn.setTitle("删除", for: .normal)
        editBtn.setTitleColor(UIColor(red: 176/255.0, green: 190/255.0, blue: 203/255.0, alpha: 1.0), for: .normal)
        editBtn.titleLabel!.font = UIFont.systemFont(ofSize: 18)
        editBtn.titleLabel!.textAlignment = .center;
        editBtn.addTarget(self, action: #selector(bianjiClick(btn:)), for: .touchUpInside)
        editBtn.tag = 21;

        let wlineLab = UILabel()
        let wlineLabX:CGFloat = TalkfunSharedTools.getMainScreen().width - 64.0
        wlineLab.frame = CGRect(x: wlineLabX, y: 14.5, width: 1.0, height: 21.0)
        wlineLab.backgroundColor = UIColor(red: 203/255.0, green: 213/255.0, blue: 222/255.0, alpha: 1.0)
         

        let deleteBtn = UIButton()
        deleteBtn.frame = CGRect(x: TalkfunSharedTools.getMainScreen().width - 43.0, y: 13.5, width: 23, height: 23)
        deleteBtn.setImage(UIImage.init(named: "HTLive.bundle/courseDownload_deleteAll"), for: .normal)
        deleteBtn.addTarget(self, action: #selector(bianjiClick(btn:)), for: .touchUpInside)
        deleteBtn.tag = 25;


        self.footerView.addSubview(lineLab)
        self.footerView.addSubview(selectAllBtn)
        self.footerView.addSubview(editBtn)
        self.footerView.addSubview(wlineLab)
        self.footerView.addSubview(deleteBtn)
    }

    // MARK: -设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataSource.count
    }
    // MARK: -创建cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:TalkfunTableViewCell = tableView.dequeueReusableCell(withIdentifier: (self.cell_Id as NSString) as String)! as! TalkfunTableViewCell
               
        cell.tf_width = self.getMainScreenBounds().size.width
        cell.tf_height = 100;
        cell.controlBtn.isHidden = false
        let model = self.dataSource[indexPath.row] as! TalkfuDownloadModel
        //标题
        cell.fileName.text = model.title;

        let progressLabelText = String.init(format: "%0.1lf/%0.1lf MB", model.downloadedSize / 1024.0 / 1024.0,model.totalSize / 1024.0 / 1024.0)
                       
        cell.progressLabel.text = progressLabelText
                        

         if (model.downloadedSize == 0) {
             cell.progressView.progress = 0;
         }else{
             cell.progressView.progress = Float(model.downloadedSize / model.totalSize)
         }
                         
         cell.progressView.tag = 20000 + indexPath.row
         if (model.totalSize != 0) {
             
             let fileProgressLabelText = String.init(format: "%0.1f%%",model.downloadedSize  / model.totalSize  * 100)
             
             cell.fileProgressLabel.text = fileProgressLabelText
         }
             cell.fileProgressLabel.tag = 30000+indexPath.row;
             cell.progressLabel.tag = 40000+indexPath.row;
                         
            let downloadStatus = model.downloadStatus as TalkfunDownloadStatus
                         
             cell.downloadBtnLabel.isHidden = false
             cell.downloadBtnLabel.textColor = UIColor.black
             cell.progressView.tintColor = nil
             cell.downloadBtnLabel.tag = 60000+indexPath.row;
             //下载完成
             if (downloadStatus == TalkfunDownloadStatusFinish) {
                 cell.progressView.progress = 1.0;
                 cell.progressView.isHidden = true;
                 cell.progressLabel.textAlignment = .left
                 cell.controlBtn.isHidden = true
               
                 let progressLabelText = String.init(format: "%0.1lf MB",model.totalSize  / 1048576)
                     
                 cell.progressLabel.text = progressLabelText
                 cell.downloadBtnLabel.isHidden = true

             }
             //正在下载
             else if (downloadStatus == TalkfunDownloadStatusStart)
             {
                 cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/beDownloading"), for: .normal)
                 cell.controlBtn.setTitle("暂停", for: .normal)
               
                 cell.downloadBtnLabel.text = "下载中";
                 cell.downloadBtnLabel.textColor = UIColor(red: 129/255.0, green: 133/255.0, blue: 136/255.0, alpha: 1.0)
              
             }
            //暂停
             else if (downloadStatus == TalkfunDownloadStatusPause)
             {
                 //TODO:重新下载
                 cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/bePaused"), for: .normal)
                 cell.controlBtn.setTitle("继续下载", for: .normal)
       
                 cell.downloadBtnLabel.text = "已暂停";
                 cell.downloadBtnLabel.textColor = UIColor(red: 129/255.0, green: 133/255.0, blue: 136/255.0, alpha: 1.0)
     
             }
             //错误
             else if (downloadStatus == TalkfunDownloadStatusError||downloadStatus == TalkfunDownloadStatusExpired)
             {
                 //下载错误
                 cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/downfail"), for: .normal)
                 cell.controlBtn.setTitle("下载错误", for: .normal)
       
                 cell.downloadBtnLabel.text = "下载失败";
                 cell.downloadBtnLabel.textColor = UIColor(red: 255/255.0, green: 59/255.0, blue: 59/255.0, alpha: 1.0)
                
                 cell.progressView.tintColor = UIColor.red
             }
            //等待
             else if (downloadStatus == TalkfunDownloadStatusPrepare)
             {
                 cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/beDownloading"), for: .normal)
                 cell.controlBtn.setTitle("等待中", for: .normal)
                 cell.downloadBtnLabel.text = "下载中";
                 cell.downloadBtnLabel.textColor = UIColor(red: 129/255.0, green: 133/255.0, blue: 136/255.0, alpha: 1.0)
             }
           //未开始
             else if (downloadStatus == TalkfunDownloadStatusUnstart)
             {
                 cell.progressView.progress = 0;
                 cell.controlBtn.setImage(UIImage.init(named: "HTLive.bundle/beDownloading"), for: .normal)
                 cell.controlBtn.setTitle("下载", for: .normal)
                cell.downloadBtnLabel.text = "等待下载";
                cell.downloadBtnLabel.textColor = UIColor(red: 129/255.0, green: 133/255.0, blue: 136/255.0, alpha: 1.0)
             }
        
        cell.controlBtn.addTarget(self, action: #selector(controlBtnClicked(btn:)), for: .touchUpInside)
        let playbackID:NSString = model.playbackID as NSString
        cell.controlBtn.tag = Int(playbackID.intValue);//开始下载的tag 与回放id 绑定
        
        cell.totalDuration.text = self.getDurationWith(float: CGFloat(model.duration)) as String
         cell.totalDuration.tag = 90000 + indexPath.row
         
//         cell.tag = 10000 + indexPath.row
      let longPressGesture = UILongPressGestureRecognizer.init(target: self, action: #selector(cellLongPress(longRecognizer:)))
        longPressGesture.minimumPressDuration = 1
        cell.addGestureRecognizer(longPressGesture)

        return cell
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        if (self.downlistTableview.isEditing) {
          
            return  UITableViewCell.EditingStyle.insert
        }else{
            return UITableViewCell.EditingStyle.delete;
        }
    }
    
    func pushLargeBack(_ model:TalkfuDownloadModel)
    
    {
        let  playbackVC = TalkfunViewLargeBack()
        playbackVC.playbackID = model.playbackID
        playbackVC.access_token = model.access_token
        playbackVC.downloadCompleted = true//下载完成
        if self.navigationController != nil {
            self.navigationController?.pushViewController(playbackVC, animated: true)
        }else
        {
            playbackVC.modalPresentationStyle = .fullScreen
            self.present(playbackVC, animated: true) {
                
            }
        }
    }
    // MARK: -选中cell
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   
        
        if (self.downlistTableview.isEditing) {

            self.selectedArray.add(indexPath)
            let deleteBtn: UIButton = self.footerView.viewWithTag(21) as! UIButton

            deleteBtn.setTitle(NSString.init(format: "删除(%d)", self.selectedArray.count) as String, for: .normal)

            deleteBtn.setTitleColor(UIColor(red: 255/255.0, green: 59/255.0, blue: 59/255.0, alpha: 1.0), for: .normal)
            
        } else {
            tableView.deselectRow(at: indexPath, animated: true)

            let model:TalkfuDownloadModel = self.dataSource[indexPath.row] as! TalkfuDownloadModel

                 // 1：普通大班回放，2：纯视频类型回放
                 let videoType = self.downloadManager.getVideoType(model.playbackID)
                 if (videoType == "1") {
                     //TODO:原生模式的点播
                     self.pushLargeBack(model)
                 }else if (videoType == "2") {
                     
                     //TODO:原生模式的点播
                     let  playbackVC = TF_SmallClassPlayBackController()
                     playbackVC.playbackID = model.playbackID;
                     playbackVC.access_token = model.access_token;

                     playbackVC.downloadCompleted = true;//下载完成
                     self.present(playbackVC, animated: true) {
                         
                     }
                 }
        }
    }
    // MARK: - 左划删除
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        self.selectedArray.add(indexPath)
        let deleteBtn: UIButton = self.footerView.viewWithTag(21) as! UIButton
 
        deleteBtn.setTitle(NSString.init(format: "删除(%d)", self.selectedArray.count) as String, for: .normal)
    }

    // MARK: -长按手势
    @objc func cellLongPress(longRecognizer:UILongPressGestureRecognizer)
    {
        if (longRecognizer.state == .began ) {
            self.becomeFirstResponder()
          
           self.downlistTableview.allowsMultipleSelectionDuringEditing = true;
            
            self.downlistTableview.setEditing(!self.downlistTableview.isEditing, animated:true )
            
            if (self.downlistTableview.isEditing) {
                if (self.downlistTableview.contentSize.height > self.view.frame.size.height - self.footerView.frame.height) {
                    self.downlistTableview.contentSize = CGSize(width: self.downlistTableview.frame.width, height: self.downlistTableview.contentSize.height + self.footerView.frame.height)
                 
                    }

                
                self.view.addSubview(self.footerView)
                self.footerView.frame = CGRect(x: 0, y: self.view.frame.size.height - 50, width: self.view.frame.size.width, height: 50)
                } else {

                    self.footerView.removeFromSuperview()
                }
          
       }
    }
    // MARK: -是否可以编辑  默认YES
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
   
    @objc func getMainScreenBounds()->CGRect
    {
        return TalkfunSharedTools.getMainScreen()
    }
    // - 按钮点击事件
    @objc func controlBtnClicked(btn:UIButton)
    {
        var tag:Int  = 0;
        
        for i in stride(from: 0, to: self.dataSource.count ,by: 1) {
 
            let model = self.dataSource[i] as! TalkfuDownloadModel
            
           let playbackID = model.playbackID as NSString
            if (playbackID.intValue == btn.tag) {
                  tag = i
                  break;
              }
              
          }
        
          if (tag > self.dataSource.count) {
              return;
          }

        let model = self.dataSource[tag] as! TalkfuDownloadModel
        if (btn.titleLabel!.text == "下载" || btn.titleLabel!.text == "继续下载" || btn.titleLabel!.text == "重新下载" || btn.titleLabel!.text == "下载错误")
        {
            self.downloadManager.startDownload(model.playbackID)

          }
          else if (btn.titleLabel!.text == "播放") {
      // 1：普通大班回放，2：纯视频类型回放
              
              let videoType:NSString =  self.downloadManager.getVideoType(model.playbackID) as NSString
              
              if (videoType == "1") {
                  //TODO:原生模式的点播
                  self.pushLargeBack(model)
     
              }else if (videoType == "2") {

                  //TODO:原生模式的点播
                  let  playbackVC = TF_SmallClassPlayBackController()
                  playbackVC.playbackID = model.playbackID;
                  playbackVC.access_token = model.access_token;

                  playbackVC.downloadCompleted = true //下载完成
                  self.present(playbackVC, animated: true) {
                      
                  }
                 
              }

              return;
          }
          else if (btn.titleLabel!.text == "暂停"){
              self.downloadManager.pauseDownload(model.playbackID)
              
              
          }
          else if (btn.titleLabel!.text == "等待中"){
              self.downloadManager.pauseDownload(model.playbackID)
             
          }
        self.downlistTableview.reloadData()
          
    }
    // pragma mark --获取时间的字符串
    @objc func getDurationWith(float:CGFloat) ->String
    {
        let totalDuration:NSInteger = NSInteger(float)
        let hour:NSInteger = NSInteger(totalDuration / 60 / 60)
        
        let minute:NSInteger = NSInteger((totalDuration - hour * 60 * 60) / 60)
        
        let second:NSInteger = NSInteger((totalDuration - hour * 60 * 60 - minute * 60))
 
        return String.init(format: "时长: %02d:%02d:%02d",hour,minute,second)
    }
  

    func showAlertView()
    {

        let alert = UIAlertController.init(title: "温馨提示", message: "确定删除该点播吗", preferredStyle:.alert)
        let cancel:UIAlertAction = UIAlertAction.init(title: "取消", style: .default) { action in
            
        }
        alert.addAction(cancel)
        let otherAction:UIAlertAction = UIAlertAction.init(title: "确认", style: .default) { action in
            self.otherActionUI()
        }
        alert.addAction(otherAction)
        if  UIDevice.current.model.hasPrefix("iPad") {
            alert.popoverPresentationController?.sourceView = self.view
            alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
        }
        
        self.present(alert, animated: true)

    }
    func otherActionUI()
    {
        let modelArray = NSMutableArray()
                           for i in stride(from: 0, to: self.selectedArray.count ,by: 1) {
       
                               let indexPath =  self.selectedArray[i] as! NSIndexPath
       
                               let model = self.dataSource[indexPath.row] as! TalkfuDownloadModel
                               modelArray.add(model)
       
                          
                               self.downloadManager.deleteDownload(model.playbackID)
       
                               }
       
                           for i in stride(from: 0, to: modelArray.count ,by: 1) {
                               let model = modelArray[i] as! TalkfuDownloadModel
                               self.dataSource.remove(model)
                           }
                           self.downlistTableview.reloadData()
       
                           self.footerView.removeFromSuperview()
                           self.resetBtn()
                           self.downlistTableview.setEditing(!self.downlistTableview.isEditing, animated: true)
    }
    @objc func bianjiClick(btn:UIButton)
       {
            if (btn.tag == 10) {
                self.downlistTableview.allowsMultipleSelectionDuringEditing = true;
                self.downlistTableview.setEditing(!self.downlistTableview.isEditing, animated: true)
               
                 if (self.downlistTableview.isEditing) {
                     if (self.downlistTableview.contentSize.height > self.view.frame.size.height - self.footerView.frame.height) {
                         self.downlistTableview.contentSize = CGSize(width: self.downlistTableview.frame.width, height: self.downlistTableview.contentSize.height + self.footerView.frame.height )
                         
                            }
                     self.view.addSubview(self.footerView)
                      
                 } else {
                     self.footerView.removeFromSuperview()
                    
                 }
            } else if (btn.tag == 20){
                self.selectedArray.removeAllObjects()
                
                btn.isSelected = !btn.isSelected;
                if (btn.isSelected) {
                    btn.setTitle("取消全选", for: .normal)
                    for i in stride(from: 0, to: self.dataSource.count ,by: 1) {
                       
                       let  indexPath =  NSIndexPath.init(row: i, section: 0)
                        self.downlistTableview.selectRow(at: indexPath as IndexPath, animated: false, scrollPosition: .top)
                        self.selectedArray.add(indexPath)
                       
                   }
                    
                    let deleteBtn:UIButton = self.footerView.viewWithTag(21) as! UIButton
            
                    deleteBtn.setTitle(NSString.init(format: "删除(%d)", self.selectedArray.count) as String, for: .normal)
                    
                    deleteBtn.setTitleColor(UIColor(red: 55/255.0, green: 59/255.0, blue: 59/255.0, alpha: 1.0), for: .normal)
    
                   
                 }else{
                
                     
                     for i in stride(from: 0, to: self.dataSource.count ,by: 1) {
                         
                         let indexPath = NSIndexPath.init(row: i, section: 0)
                         self.downlistTableview.deselectRow(at: indexPath as IndexPath, animated: true)
                         
                     }
                     
                     self.resetBtn()
                    }
            }
            
            else if (btn.tag == 21) {
                
                if(self.dataSource.count==0){
                    return;
                }
                
            
                self.showAlertView()
            }
            
            else if (btn.tag == 25) {
                
                self.footerView.removeFromSuperview()
                self.resetBtn()
            
                self.selectedArray.removeAllObjects()
                self.downlistTableview.setEditing(!self.downlistTableview.isEditing, animated: true)
                
            }
        }
    
    
    func resetBtn()
    {
        self.selectedArray.removeAllObjects()
       
        let selectAllBtn:UIButton = self.footerView.viewWithTag(20) as! UIButton
        selectAllBtn.setTitle("全选", for: .normal)
        
        let deleteBtn:UIButton = self.footerView.viewWithTag(21) as! UIButton
        deleteBtn.setTitle("删除", for: .normal)
    }
    // MARK: -下载时的状态
    func downloadStatus(_ statusModel: TalkfunDownloadStatusModel) {
        let downloadStatus = statusModel.downloadStatus
        let  playbackID:NSString = statusModel.playbackID as NSString
        var isChangedModel:Bool = false
        var Tag:Int  = 0
        for i in stride(from: 0, to: self.dataSource.count ,by: 1) {

            let  changedModel:TalkfuDownloadModel = self.dataSource[i] as! TalkfuDownloadModel;
            if (changedModel.playbackID == playbackID as String) {

                isChangedModel = true

                Tag = Int(playbackID.intValue)

                changedModel.downloadStatus = downloadStatus;

                        if (downloadStatus == TalkfunDownloadStatusStart) {

                            changedModel.duration = statusModel.duration

                            changedModel.totalSize = statusModel.totalSize;

                            let totalMB = statusModel.totalSize / 1024 / 1024
                            let writtenMB = statusModel.downloadedSize / 1024 / 1024

                            changedModel.thumb = statusModel.thumb

                            if (self.view.viewWithTag(60000+i) != nil) {
                                let  downloadBtnLabel:UILabel = self.view.viewWithTag(60000+i)! as! UILabel
                                downloadBtnLabel.textColor = nil;
                                downloadBtnLabel.text = "暂停";
                                downloadBtnLabel.textColor = nil;
                               
                                downloadBtnLabel.isHidden = false;

                            }
                            if (self.view.viewWithTag(20000+i) != nil) {
                            let progressView:UIProgressView = self.view.viewWithTag(20000 + i)! as! UIProgressView
                            progressView.tintColor = nil;
                            progressView.progress =  Float(writtenMB / totalMB);
                            }

                 
                            
                            if (self.view.viewWithTag(90000+i) != nil) {
                                let  totalDuration:UILabel = self.view.viewWithTag(90000+i)! as! UILabel
                                
                                totalDuration.text = self.getDurationWith(float: changedModel.duration)
                            }
                           

                            if (self.view.viewWithTag(Tag) != nil) {
                            let btn:UIButton = self.view.viewWithTag(Tag)! as! UIButton
                            btn.setTitle("暂停", for: .normal)
                            }
                            self.dataSource.replaceObject(at: i, with: changedModel)

                        }
                        else if (downloadStatus == TalkfunDownloadStatusPause)
                        {

                            if (self.view.viewWithTag(60000+i) != nil) {
                                let downloadBtnLabel:UILabel = self.view.viewWithTag(60000+i)! as! UILabel
                                downloadBtnLabel.text = "继续下载";
                            }
                           
                            if (self.view.viewWithTag(Tag) != nil) {
                            let btn:UIButton = self.view.viewWithTag(Tag)! as! UIButton
                            btn.setTitle("继续下载", for: .normal)
                            }
                            self.dataSource.replaceObject(at: i, with: changedModel)

                           
                        }
                        else if (downloadStatus == TalkfunDownloadStatusPrepare)
                        {

                            if (self.view.viewWithTag(60000+i) != nil) {
                                let  downloadBtnLabel = self.view.viewWithTag(60000+i)! as! UILabel
                                downloadBtnLabel.text = "等待队列";
                            }
                            
                           
                            if (self.view.viewWithTag(Tag) != nil) {
                                let btn:UIButton = self.view.viewWithTag(Tag)! as! UIButton
                                btn.setTitle("等待中", for: .normal)
                            }
                    
                            self.dataSource.replaceObject(at: i, with: changedModel)

                        }
                        else if (downloadStatus == TalkfunDownloadStatusError || downloadStatus == TalkfunDownloadStatusExpired)
                        {

                            if (self.view.viewWithTag(60000+i) != nil) {
                                let downloadBtnLabel:UILabel = self.view.viewWithTag(60000+i)! as! UILabel
                                downloadBtnLabel.text = "下载失败"
                                downloadBtnLabel.textColor = UIColor.red
                            }
                            
                            if (self.view.viewWithTag(20000+i) != nil) {
                                let progressView:UIProgressView = self.view.viewWithTag(20000 + i)! as! UIProgressView
                                progressView.tintColor = UIColor.red
                            }
                            if (self.view.viewWithTag(Tag) != nil) {
                                let btn:UIButton = self.view.viewWithTag(Tag)! as! UIButton
                                btn.setTitle("下载错误", for: .normal)
                            }

                            self.dataSource.replaceObject(at: i, with: changedModel)
                            if(downloadStatus == TalkfunDownloadStatusExpired){

                                
                                  let alertController = UIAlertController.init(title: "温馨提示", message: "资源已过期", preferredStyle: UIAlertController.Style.alert)
                                
                                   let otherAction = UIAlertAction.init(title: "确认", style: UIAlertAction.Style.default)

                                   alertController.addAction(otherAction)

                              let deviceType =  UIDevice.current.model
                                    if (deviceType == "iPad") {
                                        alertController.popoverPresentationController?.sourceView = self.view
                                        alertController.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)

                                    }
                                self.present(alertController, animated: false)


                            }



                        }
                        else if (downloadStatus == TalkfunDownloadStatusFinish) {
                            changedModel.totalSize = statusModel.totalSize;
                            changedModel.downloadedSize = statusModel.downloadedSize;
                            changedModel.duration =  statusModel.duration;


                            let totalMB = statusModel.totalSize / 1048576;
                            let writtenMB = statusModel.downloadedSize / 1048576;

                            
                            if (self.view.viewWithTag(20000+i) != nil) {
                                let progressView:UIProgressView = self.view.viewWithTag(20000 + i)! as! UIProgressView
                                progressView.progress =  Float(writtenMB / totalMB);
                                progressView.tintColor = nil;
                            }
                            
                            if (self.view.viewWithTag(30000+i) != nil) {
                                let fileProgressLabel:UILabel = self.view.viewWithTag(30000 + i)! as! UILabel
                                let fileProgressLabelText = String.init(format: "%0.1lf",changedModel.downloadedSize  / changedModel.totalSize * 100)
                                fileProgressLabel.text = fileProgressLabelText
                            }
                            
                            
                            if (self.view.viewWithTag(40000+i) != nil) {
                            let progressLabel:UILabel = self.view.viewWithTag(40000 + i)! as! UILabel
                            let progressLabelText = String.init(format: "%0.1lf%0.1lf",writtenMB ,totalMB)
                            progressLabel.text = progressLabelText
                            }


                            if (self.view.viewWithTag(60000+i) != nil) {
                            let downloadBtnLabel:UILabel = self.view.viewWithTag(60000+i)! as! UILabel
                            downloadBtnLabel.isHidden = true;
                                
                            }
                           
                            if (self.view.viewWithTag(90000+i) != nil) {
                                let totalDuration:UILabel = self.view.viewWithTag(90000+i)! as! UILabel
                                
                                totalDuration.text = self.getDurationWith(float: changedModel.duration)
                            }
                            

                            let btn:UIButton = self.view.viewWithTag(Tag)! as! UIButton
                            btn.setTitle("播放", for: .normal)
                            
                            self.dataSource.replaceObject(at: i, with: changedModel)
                            
                        }


            }
        }


        if isChangedModel  {

        }else
        {
    
            if self.delegate != nil && ((self.delegate?.getDownLoad(status:)) != nil){
       
                self.delegate?.getDownLoad(status: downloadStatus)
            }

        }
    }

    // MARK: -下载进度
    func downloadProgress(_ progressModel: TalkfunDownloadProgressModel) {
        
        let  playbackID:NSString = progressModel.playbackID as NSString

        for i in stride(from: 0, to: self.dataSource.count ,by: 1) {
   
            let  model:TalkfuDownloadModel = self.dataSource[i] as! TalkfuDownloadModel;
            if (model.playbackID == playbackID as String) {

                let totalMB = progressModel.totalSize / 1024 / 1024
                let writtenMB = progressModel.downloadedSize / 1024 / 1024
                
                model.totalSize = progressModel.totalSize;
                model.downloadedSize = progressModel.downloadedSize;
                if (self.view.viewWithTag(20000+i) != nil) {
                let progressView:UIProgressView = self.view.viewWithTag(20000 + i)! as! UIProgressView
                    progressView.progress =  Float(writtenMB / totalMB);
                
                }
                
                
                if (self.view.viewWithTag(30000+i) != nil) {
                let fileProgressLabel:UILabel = self.view.viewWithTag(30000 + i)! as! UILabel
                    let fileProgressLabelText = String.init(format: "%0.1lf",writtenMB  / totalMB * 100)
                    
                    fileProgressLabel.text = fileProgressLabelText
                }
               
                if (self.view.viewWithTag(40000+i) != nil) {
                    let progressLabel:UILabel = self.view.viewWithTag(40000 + i)! as! UILabel
                        
                    let progressLabelText = String.init(format: "%0.1lf/%0.1lf",writtenMB ,totalMB)
                        
                    progressLabel.text = progressLabelText

                    if (writtenMB == totalMB) {

                        self.sendLocalNotification(title: model.title as NSString)
                        
                        progressLabel.text =  String.init(format: "%0.1lf MB",totalMB)
                        progressLabel.textAlignment = .left;
                        self.downlistTableview.reloadData()
          
                          }
                }

              }
            }
    }
    // MARK: -下载错误
    func downloadError(_ error: TalkfuError) {
        
        let reasonDescription:String = error.reasonDescription
        let playbackID:String = error.playbackID
        let statusCode:String = error.statusCode as String
        let URL:String = error.url as String
        var  msg:String = "错误原因:" + reasonDescription
           msg = msg + "\n"
           msg = msg + "课程ID" + playbackID
           msg = msg + "\n"
           msg = msg + "状态码" + statusCode
           msg = msg + "\n"
           msg = msg + "URL" + URL
           
        let pasteboard = UIPasteboard.general
        pasteboard.string = msg;
        
        let alert =   UIAlertController.init(title: msg, message: "", preferredStyle: UIAlertController.Style.alert)
        //显示弹出框列表选择
        let playbackIDAction = UIAlertAction.init(title: "课程ID:" + playbackID, style: UIAlertAction.Style.default)
    
        let codeAction = UIAlertAction.init(title: "状态码:" + statusCode, style: UIAlertAction.Style.default)
        
        let URLAction = UIAlertAction.init(title: "URL:" + URL, style: UIAlertAction.Style.default)
       
        
        let cancelAction = UIAlertAction.init(title: "已复制报告到剪断板,可粘贴反馈", style: UIAlertAction.Style.default)
        
        alert.addAction(playbackIDAction)
        alert.addAction(codeAction)
        alert.addAction(URLAction)
        alert.addAction(cancelAction)
      
        let deviceType =  UIDevice.current.model
              if (deviceType == "iPad") {
                  alert.popoverPresentationController?.sourceView = self.view
                  alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)

            }
          self.present(alert, animated: false)

    }
    //#pragma mark 本地通知
    func sendLocalNotification(title:NSString)
    {

        // 1.创建本地通知
        let localNote = UILocalNotification()
        
        // 2.设置本地通知的内容
        localNote.timeZone = NSTimeZone.local
        localNote.repeatInterval = NSCalendar.Unit.calendar
            // 2.2.设置通知的内容
        localNote.alertBody = String.init(format: "%@ 下载完成",title)
     
            // 2.3.设置滑块的文字（锁屏状态下：滑动来“解锁”）
            localNote.alertAction = "滑动来解锁”";
            // 2.4.决定alertAction是否生效
            localNote.hasAction = false

            // 2.7.设置有通知时的音效
            localNote.soundName = "default";
            // 2.8.设置应用程序图标右上角的数字
            localNote.applicationIconBadgeNumber = 0;
        var userInfo:[NSObject : AnyObject] = [NSObject : AnyObject]()
        userInfo["type" as NSObject] = "1" as AnyObject
        localNote.userInfo = userInfo
        UIApplication.shared.presentLocalNotificationNow(localNote)
    }
    
    // 控制器的view即将显示的时候调用
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.reloDownData()
    }
    func reloDownData()
    {
        self.dataSource.removeAllObjects()
        let  playbackList:NSArray = self.downloadManager.getDownloadModelList() as NSArray
        self.dataSource.addObjects(from: playbackList as! [Any])
       
        for i in stride(from: 0, to: playbackList.count ,by: 1) {
            let model:TalkfuDownloadModel = playbackList[i] as! TalkfuDownloadModel
            if (model.downloadStatus == TalkfunDownloadStatusStart ) {
                self.downloadManager.startDownload(model.playbackID)
            }
        }
        self.downlistTableview.reloadData()
      
    }
}
